import time
import random
import requests
from urllib.parse import urlparse, urlunparse
from config.settings import MAX_RETRIES, TIMEOUT, RETRY_DELAY
from lib.core.addressExploit import operation_on_success


def switch_to_https(url):
    """如果 url 使用 http 协议，切换为 https 协议"""
    parsed_url = urlparse(url)
    if parsed_url.scheme == 'http':
        # 将 http 协议替换为 https 协议
        parsed_url = parsed_url._replace(scheme='https')
        url = urlunparse(parsed_url)
    return url

def add_scheme_if_missing(url):
    parsed_url = urlparse(url)
    if not parsed_url.scheme:  # 如果没有 scheme
        url = 'http://' + url  # 默认添加 http://
    return url

async def alive_process(url, queue, file_handler, request_handler, session):
    retries = 0  # 重试计数
    url = add_scheme_if_missing(url)
    # 禁用 302 跳转
    session.max_redirects = 0

    # 动态设置 Referer 为和 URL 一样
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
        "Accept-Language": "en-US,en;q=0.9",
        "Accept-Encoding": "gzip, deflate, br",
        "Referer": url,  # 设置 Referer 为请求的 URL
        "Connection": "keep-alive"  # 保持连接
    }

    # 更新请求头
    session.headers.update(headers)

    status_write = None
    while True:
        try:
            # 发送 HEAD 请求，禁止自动跳转
            response = session.head(url, timeout=TIMEOUT, allow_redirects=False)
            status_write = response.status_code

            if response.status_code == 200:
                print("检测到200状态码")
                print(url)
                operation_on_success(url, queue)  # 如果返回 200 状态码，执行成功操作
                return  # 请求成功后退出函数

            if response.status_code in [301, 302, 403]:
                # 对于 301、302 和 403 状态码，分别处理
                request_handler.operation_on_try(url)
                return  # 特殊状态码处理后退出

        except requests.RequestException:
            retries += 1
            if retries <= MAX_RETRIES:
                wait_time = RETRY_DELAY[min(retries, len(RETRY_DELAY) - 1)]  # 获取当前的重试延迟
                time.sleep(wait_time + random.uniform(0, 1))  # 添加随机浮动延迟，避免过多请求冲突
            else:
                if urlparse(url).scheme == 'http':  # 如果是 http 协议
                    url = switch_to_https(url)
                    print(f"超出最大重试次数，尝试将 URL 从 http 改为 https: {url}")
                    url = switch_to_https(url)
                    retries = 0
                    continue
                else:
                    file_handler.operation_on_failure(url, status_write if status_write is not None else 500)
                    return